package com.example.springboot.services.impl;

import cn.hutool.json.JSONUtil;
import com.example.springboot.domain.Admin;
import com.example.springboot.domain.Menu;
import com.example.springboot.domain.Role;
import com.example.springboot.dto.AdminDTO;
import com.example.springboot.dto.AdminDTO2;
import com.example.springboot.dto.LoginDTO;
import com.example.springboot.mapper.AdminMapper;
import com.example.springboot.mapper.MenuMapper;
import com.example.springboot.mapper.RoleMapper;
import com.example.springboot.services.AdminService;
import com.example.springboot.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    MenuMapper menuMapper;

    @Override
    public AdminDTO hasUser(LoginDTO loginDTO) {
        AdminDTO adminDTO=new AdminDTO();

        String password = adminMapper.findAdminById(loginDTO.getUsername());
        if (!loginDTO.getPassword().equals(password)) {
            return null;
        }

        //登录成功
        Admin admin = adminMapper.findAdminByName(loginDTO.getUsername());
        //添加token
        String tokenBody = JwtUtil.createToken(admin);
        adminDTO.setToken(tokenBody);
        adminDTO.setName(admin.getNickName());

//        //访问数据库，将角色对应信息存到redis
//        Role role = roleMapper.selectById(admin.getRoleId());
//        List<String> urlList = menuMapper.getRoleMenuUrl(role.getId());
//        //将对象转为Json
//        String json = JSONUtil.toJsonStr(urlList);
//        //将对象的Json存到redis
//        redisTemplate.opsForValue().set(role.getId(),json);

        return adminDTO;
    }

    @Override
    public Boolean addAdmin(AdminDTO2 adminDTO2) {

        Map<String,Object> map = new HashMap<>();
        map.put("username",adminDTO2.getUsername());
        List<Admin> adminList = adminMapper.selectByMap(map);
        if(adminList.size() != 0){
            return false;
        }

        Admin admin = new Admin();
        admin.setUsername(adminDTO2.getUsername());
        admin.setPassword(adminDTO2.getPassword());
        admin.setNickName(adminDTO2.getNickname());
        admin.setHeadImgUrl(adminDTO2.getHeadImgUrl());
        admin.setPhone(adminDTO2.getPhone());
        admin.setSex(adminDTO2.getSex());
        if(adminMapper.insert(admin) != 0){
            return true;
        };
        return false;
    }
}
